package main

import (
	"fmt"
	"log"
	"net/http"
	"os"
	"strconv"

	"github.com/julienschmidt/httprouter"
	"gorm.io/driver/mysql"
	"gorm.io/driver/sqlite"
	"gorm.io/gorm"
	"minDeploy.com/models"
	"minDeploy.com/mrouter"
)

func init() {
	dbType := os.Getenv("DB_TYPE")
	log.Println(dbType)
	if dbType == "mysql" {
		dbUser := os.Getenv("DB_USER")
		dbPass := os.Getenv("DB_PASS")
		dbHost := os.Getenv("DB_HOST")
		dbPort, err := strconv.Atoi(os.Getenv("DB_PORT"))
		if err != nil {
			panic("DB_PORT is wrong")
		}
		dbName := os.Getenv("DB_NAME")
		dns := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8&parseTime=True&loc=Local", dbUser, dbPass, dbHost, dbPort, dbName)
		models.DB, models.DBErr = gorm.Open(mysql.Open(dns), &gorm.Config{})
	} else {
		models.DB, models.DBErr = gorm.Open(sqlite.Open("./my.db"), &gorm.Config{})
	}
	if models.DBErr != nil {
		panic(models.DBErr)
	}
	models.DB.AutoMigrate(&models.DeployHistory{})

}

func main() {
	go mrouter.ResController(models.DB)
	router := httprouter.New()
	router.POST("/api/result", mrouter.Result)
	router.POST("/api/get", mrouter.Get)
	router.POST("/api/list", mrouter.List)
	router.POST("/api/install", mrouter.Install)
	router.POST("/api/uninstall", mrouter.Uninstall)
	router.POST("/api/upgrade", mrouter.Upgrade)
	log.Println("minDeploy starting......")
	log.Println(http.ListenAndServe(":8080", router))
}
